package com.ly.hotel.view.common;

import java.lang.ref.WeakReference;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ly.hotel.R;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.service.SPABackService;
import com.ly.hotel.webagent.LyAgent;

public class MsgDialog extends AlertDialog {
	private Context context;

	private WebView mWebView;
	LinearLayout mWebViewContainer;
	private LyAgent lyAgent = null;
	protected MyApplication app;
	private String msg;
	private Integer id = 0;
	private ThisHandler handlerMsg = new ThisHandler(this);
	private int autoCloseTimes = -1;	//自动关闭窗口，时间单位是毫秒

	public MsgDialog(Context context, int theme) {
	    super(context, theme);
	    this.context = context;
	}

	public MsgDialog(Context context) {
	    super(context);
	    this.context = context;
	}

	  
	private class WebViewClientDemo extends WebViewClient {
		public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
			System.out.println("onReceivedError");
			view.stopLoading();
			view.clearView();
			Message msg = handlerMsg.obtainMessage();// 发送通知，加入线程
			msg.what = 2;// 通知加载自定义出错页面
			handlerMsg.sendMessage(msg);// 通知发送！
		}
 
		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);
		}

		@Override
		// 在WebView中而不是默认浏览器中显示页面
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			view.loadUrl(url);
			return true;
		}
	}
	   
	@SuppressLint("SetJavaScriptEnabled")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		requestWindowFeature(Window.FEATURE_NO_TITLE);
//		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_msg_dialog_layout);
//		this.setFinishOnTouchOutside(false);
		Log.i("rtmsg", "MsgDialogActivity:" + this);
		initView();
		 
		mWebViewContainer = (LinearLayout)findViewById(R.id.msgWebView);
		mWebView          = new WebView(context);
		mWebViewContainer.addView(mWebView);
		
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.getSettings().setSupportMultipleWindows(true);
		mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
		mWebView.setHorizontalScrollBarEnabled(false); // 设置水平滚动条
		mWebView.setVerticalScrollBarEnabled(false); // 设置竖直滚动条
		mWebView.setBackgroundColor(0); // 设置背景色
		mWebView.setFocusableInTouchMode(false);
		if (mWebView.isHardwareAccelerated()) {
			System.out.println("开启了硬件加速");
		}
		mWebView.setOnLongClickListener(new View.OnLongClickListener() { // 去掉长按
			@Override
			public boolean onLongClick(View view) {
				return true;
			}
		});
		  
		mWebView.setWebViewClient(new WebViewClientDemo());

		mWebView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                view.requestFocus();
            }
        });
		// 把LyAgent暴露出WebView
		lyAgent = new LyAgent();
		lyAgent.initial(mWebView, context);
		lyAgent.isDialog = true;
		lyAgent.msgDialogId = id;
		mWebView.addJavascriptInterface(lyAgent, "LyAgent");

		setOnShowListener(new OnShowListener() {
			
			@Override
			public void onShow(DialogInterface arg0) {
				// TODO Auto-generated method stub
				if(msg.equals("")){
					handlerMsg.sendEmptyMessageDelayed(1, 100);
				}else{
					handlerMsg.sendEmptyMessageDelayed(0, 200);
				}
			}
		});
		if(!msg.equals("")){   
			SPABackService.putMsgActivity(id,this);
		}
		
		if(autoCloseTimes != -1 && autoCloseTimes >= 1000){
			handlerMsg.sendEmptyMessageDelayed(2, autoCloseTimes);
		}
	}
	
	private void initView(){
//		closeBtn = (TextView) findViewById(R.id.closeBtn);
		
		((TextView) findViewById(R.id.closeBtn)).setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				dismiss();
			}
		});
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public int getAutoCloseTimes() {
		return autoCloseTimes;
	}

	public void setAutoCloseTimes(int autoCloseTimes) {
		this.autoCloseTimes = autoCloseTimes;
	}

	/**
	 * handler处理消息机制
	 */
	private static class ThisHandler extends Handler {
		private WeakReference<MsgDialog> wrActivity;

		public ThisHandler(MsgDialog activity) {
			wrActivity = new WeakReference<MsgDialog>(activity);
		}

		@Override
		public void handleMessage(Message message) {
			MsgDialog act = wrActivity.get();
			if (act != null) {
				switch (message.what) {
				case 0:
					Log.i("rtmsg", "显示html:" +act.msg);
					act.mWebView.getSettings().setDefaultTextEncodingName("UTF-8") ;
					act.mWebView.loadData(act.msg, "text/html; charset=UTF-8", null);
					break;	
					
				case 1:
					act.mWebView.clearCache(false);
					act.mWebView.loadUrl("file:///android_asset/www/tips.html");
					break;
					
				case 2:
					act.dismiss();
					break;
				}
			}
		}
	}
}
